<template>
  <div class="add-employee">
    <button class="add-employee-header" @click="() => $router.push('/staff')">
      <el-icon>
        <ArrowLeftBold />
      </el-icon>返回
      <text>|</text>
    </button>
    <div class="add-employee-title" v-if="isEdit">修改医护</div>
    <div class="add-employee-title" v-else>添加医护</div>


  </div>
  <div class="add-employee-content">
    <el-form :inline="true" ref="ruleFormRef" style="max-width: 800px" :model="ruleForm" :rules="rules"
      label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
      <el-form-item label="医护名称:" prop="name" style="width: 350px; margin-right: 100px;">
        <el-input v-model="ruleForm.name" placeholder="请输入员工姓名" />
      </el-form-item>

      <el-form-item label="部门分类:" prop="departmentId" style="width: 250px;">
        <el-select-v2 v-model="ruleForm.departmentId" placeholder="选择分类部门" :options="options" />
      </el-form-item>

      <el-form-item label="预约价格:" prop="price" style="width: 350px; margin-right: 100px;">
        <el-input v-model="ruleForm.price" placeholder="请输入需要预约价格" />
      </el-form-item>
      <el-form-item label="医护图片:" prop="image" style="width: 350px; margin-right: 300px;">
        <el-upload class="avatar-uploader" 
        action="http://localhost:7070/api/admin/common/upload" 
        method="post"
        name="file" 
        :headers="headers"
        :show-file-list="false"
        list-type="picture" 
        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="ruleForm.image" :src="ruleForm.image" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="医护描述:" prop="description" style="width: 600px;">
        <el-input v-model="ruleForm.description" type="textarea" />
      </el-form-item>
    </el-form>
    <div class="add-employee-btn">
      <el-button color="#626aef" @click="submitForm(ruleFormRef)">提交</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </div>

  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
// import { addEmployee, queryEmployeeById, updateEmployee } from '@/api/employee'
import { addStaff, queryStaffById, updateStaff } from '@/api/staff'
import { queryDepartmentPage } from '@/api/department'
import router from '@/router';
import { useUserStore } from '@/stores/user.js'

const userStore = useUserStore()
const headers = ref({ 'token': userStore.viewToken })
const handleAvatarSuccess = (response, uploadFile) => {
    ruleForm.image = response.data; // 同步到form.image
    ElMessage.success('上传成功');
}

const beforeAvatarUpload = (rawFile) => {
    // console.log(rawFile);
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/gif' && rawFile.type !== 'image/webp') {
        ElMessage.error('必须为图片格式！')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像图片大小不能超过 2MB！')
        return false
    }
    return true
}

const formSize = ref('default')
const ruleFormRef = ref(null)
const ruleForm = reactive({
  name: '',
  departmentId: '',
  price: '',
  image: '',
  description: '',
})

const rules = reactive({
  name: [
    { required: true, message: '请输入医护名称', trigger: 'blur' },
    { min: 1, message: '名称长度不能小于 1 个字符', trigger: 'blur' },
  ],
  departmentId: [
    { required: true, message: '请选择分类部门', trigger: 'change' },
  ],
  price: [
    { required: true, message: '请输入预约价格', trigger: 'blur' },
  ],
  image: [
    { required: true, message: '请上传医护图片', trigger: 'change' },
  ],
  description: [
    { required: true, message: '请输入医护描述', trigger: 'blur' },
    { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' },
  ],
})

const options = ref([])
// 加载部门分类数据的函数
const fetchDepartmentOptions = async () => {
  // 构建分页参数
  const params = {
    page: 1,
    pageSize: 1000,
  }
  await queryDepartmentPage(params).then((res) => {
    // console.log(res);
    options.value = res.data.records.map((item) => {
      return {
        label: item.name,
        value: item.id,
      }
    })
  })
  .catch(() => {
     ElMessage.error('加载部门分类失败！')
   })
}

// 提交表单
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // console.log('验证成功！', ruleForm)
      if (isEdit.value) {
        // 修改
        await updateStaff(ruleForm)
          .then(() => {
            ElMessage.success('修改成功！')
            router.push('/staff')
          })
          .catch(() => {
            ElMessage.error('修改失败！')
          })

      } else {
        console.log('添加', ruleForm);
        await addStaff(ruleForm).then(() => {
          ElMessage.success('提交成功！')
          resetForm(formEl)
        })
          .catch(() => {
            ElMessage.error('提交失败！')
          })
      }

    } else {
      // console.log('提交错误！', fields)
    }
  })
}

// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

// 判断是否存在id
const isEdit = ref(false)

onMounted(async () => {
  fetchDepartmentOptions()
  // console.log(router.currentRoute.value.query);
  const id = router.currentRoute.value.query.id;
  if (id) {
    isEdit.value = true
    queryStaffById(id).then((res) => {
      Object.assign(ruleForm, res.data)
    })

  }
})

</script>

<style lang="scss">
.add-employee {
  display: flex;
  align-items: center;

  .add-employee-header {
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    background: none;
    color: inherit;
    padding: 0;
    cursor: pointer;

    .el-icon {
      margin-right: 3px;
    }

    text {
      margin: 0 10px;
      color: #999;
      font-size: 14px;
      border-radius: 5px;
    }
  }

  .add-employee-title {
    font-size: 18px;
  }
}

.add-employee-content {
  margin-top: 10px;
  padding: 10px;
  background-color: #fff;

  .el-form {
    margin: 20px 0 0 100px;

    .avatar-uploader {
      width: 178px;
      height: 178px;
      display: block;
      border: 2px dashed #d9d9d9;

      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
      }

      .avatar {
        width: 178px;
        height: 178px;

      }
    }
  }

  .add-employee-btn {
    margin-top: 30px;
    padding-top: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-top: 1px solid var(--el-border-color);

  }
}
</style>